package com.mission.schedule.activity;

import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.mission.schedule.CommonDialog.LocalSynServiceDialog;
import com.mission.schedule.R;
import com.mission.schedule.applcation.App;
import com.mission.schedule.clock.WriteAlarmClock;
import com.mission.schedule.constants.ShareFile;
import com.mission.schedule.constants.URLConstants;
import com.mission.schedule.service.UpdataTagService;
import com.mission.schedule.utils.ActivityManager1;
import com.mission.schedule.utils.GetDeviceId;
import com.mission.schedule.utils.NetUtil;
import com.mission.schedule.utils.ProgressUtil;
import com.mission.schedule.utils.SharedPrefUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class OLoginActivity extends BaseActivity {
    SharedPrefUtil sharedPrefUtil = null;
    ProgressUtil progressUtil;
    Context context;
    ActivityManager1 activityManager = null;
    LinearLayout bacl_ll;
    @Override
    protected void setListener() {

    }

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_ologin);
        activityManager = ActivityManager1.getInstance();
        context = this;
        sharedPrefUtil = new SharedPrefUtil(context, ShareFile.USERFILE);
        String userName = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.USERNAME, "");
        bacl_ll = findViewById(R.id.bacl_ll);
        final EditText name = findViewById(R.id.name);
        name.setText(userName);
        final EditText code = findViewById(R.id.code);
        findViewById(R.id.login).setOnClickListener(v -> {
            if (name.getText().toString().isEmpty() || code.getText().toString().isEmpty()) {
                Toast.makeText(this, "昵称或安全码不能为空", Toast.LENGTH_SHORT).show();
                return;
            }
            login(name.getText().toString(), code.getText().toString()) ;
        });
        findViewById(R.id.bacl_ll).setOnClickListener(v -> finish());
    }

    private void login(final String name, final String code) {
        progressUtil = new ProgressUtil();
        progressUtil.ShowProgress(this, true, true, "登录...");
        new Thread(() -> {
            StringRequest stringRequest = new StringRequest(Request.Method.POST, URLConstants.HOST + "/user_regisTbUserByUnionNumberTimetable.do",
                    result -> {
                        progressUtil.dismiss();
                        Gson gson = new Gson();
                        PhoneCodeLoginNewActivity.LoginBean loginBean = gson.fromJson(result, PhoneCodeLoginNewActivity.LoginBean.class);
                        if (loginBean.status == 0) {
                            List<PhoneCodeLoginNewActivity.LoginBean.ListBean> list = loginBean.list;
                            if (list != null && list.size() > 0) {
                                ExitDailog(list);
                            } else {
                                Toast.makeText(this, "登录失败", Toast.LENGTH_SHORT).show();
                            }
                        } else if(loginBean.status == 4){
                            Toast.makeText(this, "用户不存在", Toast.LENGTH_SHORT).show();
                        } else if(loginBean.status == 5){
                            Toast.makeText(this, "安全码错误", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(this, "登录失败", Toast.LENGTH_SHORT).show();
                        }
                    }, volleyError -> {
                        progressUtil.dismiss();
                        Toast.makeText(OLoginActivity.this, "网络异常,请检测网络", Toast.LENGTH_SHORT).show();
                    }) {
                @Override
                protected Map<String, String> getParams() {
                    Map<String, String> map = new HashMap<>();
                    map.put("uname", name);// "52432"
                    map.put("yzm", code);
                    map.put("data", "TimeSheet_A_"+ GetDeviceId.getDeviceId(OLoginActivity.this).replaceAll(":","0").replaceAll("%", "1"));
                    return map;
                }
            };
            stringRequest.setTag("downUserNewLy");
            stringRequest.setRetryPolicy(new DefaultRetryPolicy(100000, 1, 1.0f));
            App.queues.add(stringRequest);
        }).start();
    }


    private void ExitDailog(List<PhoneCodeLoginNewActivity.LoginBean.ListBean> list) {
        final android.app.AlertDialog builder = new android.app.AlertDialog.Builder(context).create();

        builder.show();
        Window window = builder.getWindow();
        android.view.WindowManager.LayoutParams params = window.getAttributes();// 获取LayoutParams
        params.alpha = 0.92f;
        window.setAttributes(params);// 设置生效
        window.setContentView(R.layout.dialog_alter);
        TextView delete_ok = window.findViewById(R.id.delete_ok);
        delete_ok.setText("上传数据");
        delete_ok.setTextColor(Color.RED);
        delete_ok.setOnClickListener(v -> {
            if (NetUtil.getConnectState(context) != NetUtil.NetWorkState.NONE) {
                LocalSynServiceDialog localSynServiceDialog = new LocalSynServiceDialog(context, R.style.dialog_translucent, getWindowManager());
                localSynServiceDialog.show();
                localSynServiceDialog.setCallBack(() -> {
                    clearApp();
                    loginToMain(list);
                });
            } else {
                Toast.makeText(context, "请检查您的网络!", Toast.LENGTH_LONG).show();
            }
            builder.dismiss();
        });
        TextView cancle_tv = window.findViewById(R.id.cancle_tv);
        cancle_tv.setText("继续退出");
        cancle_tv.setOnClickListener(v -> {
            builder.dismiss();
            clearApp();
            loginToMain(list);
        });
        TextView delete_tv = window.findViewById(R.id.delete_tv);


        delete_tv.setText("本地还有未同步的数据，如果继续切换，数据将会丢失，点击返回按钮可以取消操作,否则将停留在此页面。请您在网络畅通的环境，先上传数据，再切换账号。");

    }

    private void loginToMain(List<PhoneCodeLoginNewActivity.LoginBean.ListBean> list) {
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.NewMyFoundFenXiangFirst, "1");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.ISYOUKE, "1");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.USEREMAIL, list.get(0).uEmail);
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.TELEPHONE, list.get(0).uMobile);
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.USERID, list.get(0).uId + "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.USERNAME, list.get(0).uNickName);
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.USERSTATE, "1");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.USERBACKGROUNDPATH, list.get(0).uBackgroundImage);
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.PERSONREMARK, list.get(0).uPersontag);
        if (!"".equals(list.get(0).uPortrait)) {
            String str = list.get(0).uPortrait;
            str = str.replace("\\", "");
            sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.USERPHOTOPATH, str);
        }
        sharedPrefUtil.putString(getApplication(), ShareFile.USERFILE, ShareFile.FIRSTOPENAPP, "1");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.U_ACC_NO, list.get(0).uAccNo);
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.ISYOUKE, list.get(0).uIsActive + "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.SHUNYANTYPE, "0");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.ISNEWYOUKE, "-1");
        Intent tagintent = new Intent(context, UpdataTagService.class);
        tagintent.setAction("UpdataTagService");
        tagintent.putExtra("down", "downtag");
        tagintent.setPackage(getPackageName());
        startService(tagintent);
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.FIRSTLOGIN, "0");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.ISNEWLOCAL, "0");
        sharedPrefUtil.putString(getApplicationContext(), ShareFile.USERFILE, ShareFile.LOGINTYPE, "0");
        finish();
        startActivity(new Intent(context, MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
        sendBroadcast(new Intent("loginReceiver"));
    }

    private void clearApp() {
        bacl_ll.setVisibility(View.GONE);
        WriteAlarmClock.clearAlarmClock(context);
        if (!"".equals(sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.TELEPHONE, ""))) {
            sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.TELEPHONE, "");
        } else {
            sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.USEREMAIL, "");
        }
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.WELCOMETOLOGIN, "0");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.ZDTX, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.ZDTX, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.BDTX, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.ISTX, "1");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.QIANDAOSTRING, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.ISADMIN, "0");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.USERID, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.USERNAME, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.USERBACKGROUNDPATH, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.USERPHOTOPATH, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.USERSTATE, "0");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.FIRSTLOGIN, "0");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.U_ACC_NO, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.MAXFOCUSID, "0");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.OUTWEEKFAG, "0");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.UPDATESETTIME, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.UPDATENOTESETTIME, "2017-01-01%2B00:00:00");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.DOWNSCHTIME, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.DOWNREPTIME, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.RINGSTATE, "0");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.ISYOUKE, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.DOWNTAGDATE, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.OPENSTYLESTATE, "2");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.FRIENDDOWNSCHTIME, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.FRIENDDOWNRepTIME, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.FRIENDDOWNOldTIME, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.PUSH_ALIAS, "0");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.REFRESHFRIEND, "0");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.FIRSTDOWNFOCUSSCH, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.SHOUCANGDATA, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.DOWNNEWFOCUSSHARESCHDATE, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.DOWNNEWFOCUSSHAREREPDATE, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.KuaiJieSouSuo, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.SHAREDATA, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.LOCALPATH, "1");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.ISSJMOSTIMAGE, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.CUSTIOMMOSTIMAGE1, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.CUSTIOMMOSTIMAGE2, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.CUSTIOMMOSTIMAGE3, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.CUSTIOMMOSTIMAGE4, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.CUSTIOMMOSTIMAGE5, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.CUSTIOMMOSTIMAGE6, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.CUSTIOMMOSTIMAGE7, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.DQRBEFORETIME, "4320");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.ZJF, "0");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.UNTASKEND, "1");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.PERSONREMARK, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.PERSONDOWNTIME, "2016-01-01%2B00:00:00");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.ISNEWYOUKE, "0");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.WEEKCOLOR1, "2");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.MONTHCOLOR2, "3");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.YEARCOLOR3, "4");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.ISMOSTIMAGE, "");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.MORNINGTIME, "07:58");
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.NIGHTTIME, "20:58");
        App.getDBcApplication().douleClear();
        activityManager.doAllActivityFinish();
        sharedPrefUtil.putString(context, ShareFile.USERFILE, ShareFile.PERSONDOWNTIME, "2016-01-01");
        Intent intentappwidget = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
        Bundle extras = new Bundle();
        intentappwidget.putExtras(extras);
        context.sendBroadcast(intentappwidget);
    }


    @Override
    protected void init(Bundle savedInstanceState) {

    }

    @Override
    protected void setAdapter() {

    }
}
